<template>


  <div class="page-all-content">



    <div class="header-content"> <img class="header-icon" referrerpolicy="no-referrer"
        src="@/assets/img/module1/page1top2.png" />
      <span class="header-title">空域规划方案</span>
    </div>
    <!-- GIS展示 -->
    <div id="cesiumContainer-module2-ps"></div>

    
    <!-- <img class="image_3" referrerpolicy="no-referrer" src="@/assets/img/module2/temp/tempgis.png" /> -->

    <div class="left-panel-container">
      <div class="img_left_title">
        <img src="@/assets/img/module2/content.png" style="width: 100%" />
        <img src="@/assets/img/module2/snailtitleicon.png" style="position: absolute; top: -10%; left: 6%" />
        <span class="text_left_title">空域方案列表</span>

      </div>
      
      <button v-if="!tableVisible" class="table-button-display"  @click="tableVisible = true">显示</button>
      <button v-if="tableVisible" class="table-button-hidden" @click="tableVisible = false">隐藏</button>


      <!-- 功能输入按钮部分 -->
      <div v-if="tableVisible" class="table-actions">

        <!-- 搜索框 -->
        <input type="text" v-model="searchQuery" placeholder="请输入关键字" class="search-input" />
        <!-- 查询按钮 -->
        <button @click="filterTable" class="filter-button"></button>
        <!-- 排序选择 -->
        <select v-model="selectedSort" class="sort-select" @change="sortTable">
          <option value="application_acceptance_time" class="sort-select-item">按时间最新</option>
          <option value="id" class="sort-select-item">按序号排序</option>
        </select>

        <button @click="sortInverse" class="sort-button"></button>





        <!-- 刷新按钮 -->
        <!-- <el-button @click="refreshTable" icon="el-icon-refresh" type="primary">刷新</el-button> -->

      </div>

      <!-- 表格内容 -->
      <div v-if="tableVisible" class="table-context">
        <CustomTable :data="tableData" :columns="columns" @viewDetails="handleViewDetails" @viewDetailsHover="handleViewDetailsHover" @hoverLeave="hoverLeave"
          height="100%" ref="customTable" />



        <!-- <div class="table-container2">
        <SimpleTable :title="'某某某文件列表'" :tableData.sync="fileData" :rowHeight="30" @row-selected="handleRowSelected" />
        <div style="color: azure;">
          <h4>选中的数据：</h4>
          <pre>{{ selectedRow }}</pre> 
        </div>
      </div> -->


      </div>

    </div>
    <!-- <CustomTable :data="tableData" :columns="columns" :pageSize="8" @viewDetails="handleViewDetails" /> -->



    <!-- <h3>模块一、模块四、模块五可复用列表组件</h3> -->
    <!-- <div class="table-container2">
        <SimpleTable :title="'某某某文件列表'" :tableData.sync="fileData" :rowHeight="30" @row-selected="handleRowSelected" />
        <div style="color: azure;">
          <h4>选中的数据：</h4>
          <pre>{{ selectedRow }}</pre> 
        </div>
      </div> -->







    <!-- 弹窗内容 -->
    <div class="right-panel-container">
      <CustomDialog :visible.sync="statusDialogVisible" :selectedDetails="selectedDetails"
        @submitClickTransfer="submitVisibleChange" @withdrawClickTransfer="withdrawVisibleChange" ref="statusDialog" @entity-change="entityViewChange" >
      </CustomDialog>

    </div>

    <div class="table-wrapper">


      <!-- 操作栏：排序方式、搜索框、查询按钮、刷新按钮 -->





      <!-- 表格内容 -->



    </div>

    <CustomSubmitDialogConfirm :visible.sync="statusSubmitDialogVisible" :operationtype=true :id=this.selectedDetails.id :status=this.selectedDetails.approvalStatus width="600px" height="300px" @updateData="updateSelectedData">


    </CustomSubmitDialogConfirm>

    <CustomSubmitDialogConfirm :visible.sync="statusWithdrawDialogVisible" :operationtype=false :id=this.selectedDetails.id :status=this.selectedDetails.approvalStatus width="600px" height="300px" @updateData="updateSelectedData">

</CustomSubmitDialogConfirm>

  </div>

</template>

<script>
import CustomTable from '@/components/CustomTableModule2PlanningScheme.vue';
import CustomSubmitDialogConfirm from '@/components/CustomDialogModule2SubmitConfirm.vue';
import CustomDialog from '@/components/CustomDialogModule2PSInformation.vue';
import { drawCylinderAreaM1, draw3DRectangularPipelineTrackM1_2, draw3DPolygonalPrismM1 } from '@/utils/draw3D-module2.js';
import axios from 'axios';
export default {
  name: "Module2PlanningScheme",
  components: {
    CustomTable,
    CustomSubmitDialogConfirm,
    CustomDialog

  },
  data() {
    return {
      tableVisible: true, // 控制表格显示
      statusSubmitDialogVisible: false,  // 状态弹窗显示
      statusWithdrawDialogVisible:false,
      statusDialogVisible: false,
      selectedDetails: {}, // 存储选中的行数据
      selectedSort: 'id', // 默认按序号排序
      searchQuery: '',  // 搜索关键字
      inverseSort: true, // 排序顺序，默认升序
      fileList: [], // 上传文件列表
      tableData: [], // 表格数据从服务器获取
      gisdata:[],
      entityMap : {}, // 存储GIS实体对象
      viewer: null, // cesium 视图对象
      columns: [
        { prop: 'id', label: '#',width: '10%' },
        { prop: 'programName', label: '空域使用说明',width: '45%' },
        { prop: 'applicationAcceptanceTime', label: '创建时间',width: '45%' },
      ],
    }

  },
  created() {
    // 页面加载时获取数据
    this.fetchTableData();
    // this.initializeCesium(); // 初始化Cesium
  },

  mounted() {
   
    this.initializeCesium();
 
  },

  beforeDestroy() {
    this.cesiumDestroy();
  },

  methods: {

    // 获取GIS数据
    async initializeCesium() {
      try {
        console.log("开始初始化Cesium");
        this.viewer = new Cesium.Viewer('cesiumContainer-module2-ps',
          {
            geocoder: false, //搜索工具
            homeButton: false, //平滑视角默认视角
            sceneModePicker: false, //2D/3D切换
            baseLayerPicker: false, //底图切换
            navigationHelpButton: false, //帮助按钮
            animation: false, //动画播放
            fullscreenButton: false, //全屏按钮
            timeline: false //时间轴
          

          }

        );
        this.viewer.scene.frameState.creditDisplay.container.style.display = 'none';
        console.log("initializeCesium")
        // console.log("viewer", viewer)
        // const container = document.getElementById('cesiumContainer-module2-ps');
        // const rect = container.getBoundingClientRect();


        // 后续变成后端汆传输的数据
        // 定义每个五边形的顶点位置，单位为经度、纬度（从Degrees定义）
       

        this.viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(113.5, 22.1, 100000)
        });


      } catch (error) {
        console.error('Cesium initialization failed:', error);


      


      }
    },


    async drawgis(row) {
      try {
        this.viewer.entities.removeAll();
        this.refreshGISdata(); // 刷新gis数据
        this.fetchGISData(row); // 获取gis数据
        let currentLabelEntity = null;

        const { circular, polygonal, straight } = this.gisdata;
        const entitiesToFlyTo = [];
        console.log("得到GIS数据")


        // 先画圆形
        // console.log("circular.length", circular.length)
        if (circular.length > 0) {
          
          circular.forEach((coord, index) => {
            console.log(coord.minAltitude)
            console.log(coord.maxAltitude)
            const entity = drawCylinderAreaM1(
              this.viewer,
              coord.longitude,
              coord.latitude,
              // coord.minAltitude,
              // coord.maxAltitude,
              100,

              800,
              // coord.radius,
              1200,
              'GREEN',
              0.5,

            );
            if (entity) {
              

              entity.properties = new Cesium.PropertyBag({
              index: coord.index,  // 自定义index字段
              activeIndex: coord.activeidentityid,  // 自定义activeIndex字段
            });

              //暂时去掉
              // this.gisdata.circular[index].entity = entity; 
              this.addEntity(coord.activeidentityid,coord.index,entity);
              // console.log("entity",entity)
              // console.log("this.gisdata.circular[index]",this.gisdata.circular[index])
              entitiesToFlyTo.push(entity);
            }
          });
        }
        // console.log("entitiesToFlyTo.length", entitiesToFlyTo.length)
      // 绘制多边形
      // console.log("polygonal.length", polygonal.length)
        if (polygonal.length > 0) {
          polygonal.forEach((track, index) => {
            // console.log("绘制多边形柱状体传入的数据", track)
            // console.log("经纬度坐标信息", track.coordinates.map(coord => [coord.longitude, coord.latitude]).flat())
            // console.log("最小高度", track.minAltitude)
            const entity = draw3DPolygonalPrismM1(
              this.viewer,
              track.coordinates.map(coord => [coord.longitude, coord.latitude]).flat(),
              track.minAltitude,
              track.maxAltitude,
              // 100,
              // 800,
              'BLUE',
              0.5,
             
            );
            // console.log("entity",entity)
            // console.log("index",index)
            if (entity) {
              entity.properties = new Cesium.PropertyBag({
              index: track.index,  // 自定义index字段
              activeIndex: track.activeidentityid,  // 自定义activeIndex字段
            });
              //暂时去掉
              // this.gisdata.polygonal[index].entity = entity;
              entitiesToFlyTo.push(entity);
              this.addEntity(track.activeidentityid,track.index,entity);
            }
          });
        }
        // console.log("entitiesToFlyTo.length", entitiesToFlyTo.length)

 // 绘制长方体管道轨迹（如果有的话）
//  console.log("straight.length", straight.length)
 if (straight.length > 0) {
          console.log("绘制长方体管道传入的数据", straight);
          straight.forEach((track, index) => {
            const coordinates = track.coordinates.map(coord => [coord.longitude, coord.latitude, coord.altitude]).flat();
            const pointNames = track.activeidentityid; // 获取每个轨迹点的名字

            // Ensure sizes array has the correct length
            const sizes = new Array(coordinates.length / 3 - 1).fill([100, 50]); // 对应生成每段长宽

            // Check if sizes length matches coordinates length - 1
            if (sizes.length !== coordinates.length / 3 - 1) {
              console.error('Sizes array length does not match coordinates array length minus one');
            } else {
              const entities = draw3DRectangularPipelineTrackM1_2(
                this.viewer,
                coordinates,
                sizes,
                'YELLOW',
                // pointNames // 传递轨迹点名字数组
              );
              if (entities) {
              // console.log("typeof entities",entities);
              entities.forEach((entity, num) => {
              entity.properties = new Cesium.PropertyBag({
              index: track.index,  // 自定义index字段
              activeIndex: track.activeidentityid,  // 自定义activeIndex字段,
            });
  
              entitiesToFlyTo.push(entity);
              console.log('添加实体',num)
          
          }
            
            )
              //暂时去掉
              this.addEntity(track.activeidentityid,track.index,entities);
                // this.gisdata.straight[index].entity = entities;

              }
            }
          });
        }
        // console.log("entitiesToFlyTo.length", entitiesToFlyTo.length)

        // console.log("entitiesToFlyTo.length", entitiesToFlyTo.length)
        // 调整实体视角
        if (entitiesToFlyTo.length > 0) {
          this.viewer.flyTo(entitiesToFlyTo, {
            duration: 2,
            offset: {
              heading: Cesium.Math.toRadians(0),
              pitch: Cesium.Math.toRadians(-30),  // 视角抬高一些
              roll: 0
            }
          });
        }

        console.log("entityMap", this.entityMap)

        // 鼠标左键点击事件
        this.viewer.screenSpaceEventHandler.setInputAction((movement) => {
          // 清除之前的标签实体
          if (currentLabelEntity) {
            this.viewer.entities.remove(currentLabelEntity);
            currentLabelEntity = null;
          }

          const pickedObject = this.viewer.scene.pick(movement.position,5);
        
          if (pickedObject&&pickedObject.id && pickedObject.id.properties && pickedObject.id.properties.activeIndex)
         { // console.log("pickedObject", pickedObject)
          // console.log("pickedObject.id", pickedObject.id)
          // console.log("pickedObject.id.properties", pickedObject.id.properties)
          // console.log("pickedObject.id.properties.index", pickedObject.id.properties.index.getValue())
          // console.log("pickedObject.id.properties.activeIndex", pickedObject.id.properties.activeIndex.getValue())
          // console.log(this.$refs.statusDialog)
          // this.$refs.statusDialog.testClick()
          const id1 = pickedObject.id.properties.activeIndex.getValue()
          const id2 = pickedObject.id.properties.index.getValue()
          this.$refs.statusDialog.clickGis(id1,id2)
          this.viewer.flyTo(this.getEntity(id1,id2))
        }
          
        
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)




        console.log('方案地图组件渲染成功');
      }catch (error) {
        console.error('方案地图组件渲染失败', error);
      }

    },

    // 销毁Cesium实例
    cesiumDestroy() {
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
      console.log(this.viewer);
    },

    async fetchGISData(row){

      console.log('row.takeoffLandInfo',row.takeoffLandInfo)
      // 更新GIS数据，使gisdata的值符合作图的形式
      row.takeoffLandInfo&&row.takeoffLandInfo.forEach((detail, index) => {
        console.log('typeof takeoffland detail',detail)
        this.takeofflandpush(detail,index,'main1')


        // if (detail.type === '圆形') {
        //   this.cirularpush(detail.pointInfo,index,'main1')
        //   console.log('圆形更新');
        // }else if (detail.type === '多边形') {
        //   this.polygonalpush(detail.pointInfo,index,'main1')
        //   console.log('多边形更新')
        // }else if (detail.type === '点线形'){
        //   this.straightpush(detail.pointInfo,index,'main1')
        //   console.log('点线形更新')
        // }
        // console.log("飞机起降场信息更新");
      });

      row.airlineInfo&&row.airlineInfo.forEach((detail, index) => {
        if (detail.type === '圆形') {
          this.cirularpush(detail.pointInfo,index,'main2')
          console.log('圆形更新');
        }else if (detail.type === '多边形') {
          this.polygonalpush(detail.pointInfo,index,'main2')
          console.log('多边形更新')
        }else if (detail.type === '点线形'){
          this.straightpush(detail.pointInfo,index,'main2')
          console.log('点线形更新')
        }
        // console.log("航线信息更新");
      });

      row.workInfo&&row.workInfo.forEach((detail, index) => {
        if (detail.type === '圆形') {
          this.cirularpush(detail.pointInfo,index,'main3')
          console.log('圆形更新');
        }else if (detail.type === '多边形') {
          this.polygonalpush(detail.pointInfo,index,'main3')
          console.log('多边形更新')
        }else if (detail.type === '点线形'){
          this.straightpush(detail.pointInfo,index,'main3')
          console.log('点线形更新')
        }
        // console.log("作业信息更新");
      });

      row.specialInfo&&row.specialInfo.forEach((detail, index) => {
        if (detail.type === '圆形') {
          this.cirularpush(detail.pointInfo,index,'main4')
          console.log('圆形更新');
        }else if (detail.type === '多边形') {
          this.polygonalpush(detail.pointInfo,index,'main4')
          console.log('多边形更新')
        }else if (detail.type === '点线形'){
          this.straightpush(detail.pointInfo,index,'main4')
          console.log('点线形更新')
        }
        // console.log("特殊信息更新");
      });

    // console.log(this.gisdata.circular)

    },

    // 获取表格数据
    async fetchTableData() {
      try {
        const response = await axios.post('http://47.99.75.194:8082/module2/search', null,
          {
            params:
            {
              sort: this.selectedSort,
              keyword: this.searchQuery,
              order: this.inverseSort,
            },

          });
        if (response.data.code === 0) {
          this.tableData = response.data.data;
        }
        this.refreshGISdata();
        
      } catch (error) {
        console.error('获取表格数据失败', error);
      }

    },

    updateSelectedData() {
      this.fetchTableData();
      this.statusDialogVisible=false;
      console.log('父组件更新成功');

    },
    sortTable() {
      // 重新获取排序后的数据
      this.fetchTableData();
    },
    sortInverse() {
      this.inverseSort = !this.inverseSort;
      // console.log(this.inverseSort);
      this.fetchTableData();

    },

    filterTable() {
      // 触发搜索过滤，重新获取数据
      this.fetchTableData();
    },
    refreshTable() {
      // 刷新表格数据，重置搜索和排序
      this.selectedSort = 'id';
      this.searchQuery = '';
      this.fetchTableData();
    },
    handleViewDetails(row) {
      this.selectedDetails = row; // 将点击的行数据保存
      this.statusDialogVisible = true; // 显示弹窗
      this.$refs.statusDialog.refreshChange();
      this.drawgis(row);


    },
    handleViewDetailsHover(row) {
      this.selectedDetails = row; // 将点击的行数据保存
      this.statusDialogVisible = true; // 显示弹窗
    },
    hoverLeave() {
      this.statusDialogVisible = false;
    },
    submitVisibleChange() {
      this.statusSubmitDialogVisible = true;
    },
    withdrawVisibleChange() {
      this.statusWithdrawDialogVisible = true;
    },


    // 添加实体函数
addEntity(id1, id2, entity) {
    const key = `${id1}-${id2}`;  // 组合 id1 和 id2 作为唯一键
    this.entityMap[key] = entity;  // 存储实体
},

// 获取实体函数
getEntity(id1, id2) {
    const key = `${id1}-${id2}`;  // 组合 id1 和 id2 生成键
    return this.entityMap[key];  // 获取对应实体
},
entityViewChange(id1,id2){
  // console.log(id1,id2);

    console.log(id1,id2);
    if (Cesium.defined(this.getEntity(id1,id2))){
        this.viewer.flyTo(this.getEntity(id1,id2))}

},

    refreshGISdata(){
      this.gisdata={
          circular: [],
          polygonal: [],
          straight: []
        };
      // console.log("刷新GIS数据");
    },
    takeofflandpush(detail,index,infoid){
      // 第一句话后续可以去掉 注意数据类型
      // console.log("typeof detail",typeof detail);
      // console.log("降落机场detail",detail);
      // detail=JSON.parse(detail.replace(/([{,])\s*([a-zA-Z_]\w*)\s*:/g, '$1"$2":'));
      this.gisdata.circular.push(
        {
            longitude: detail.longitude,
            latitude: detail.latitude,
            minAltitude: 0,
            maxAltitude: 1000,
            radius: 1000,
            activeidentityid:infoid,
            index: index
            })
          // console.log(this.gisdata.circular);
    },

    cirularpush(detail,index,infoid){
      // 第一句话后续可以去掉 注意数据类型
      console.log("typeof detail",typeof detail);
      console.log("圆形detail",detail);
      // detail=JSON.parse(detail.replace(/([{,])\s*([a-zA-Z_]\w*)\s*:/g, '$1"$2":'));
      this.gisdata.circular.push(
        ...detail.map(coord => ({
            longitude: coord.longitude,
            latitude: coord.latitude,
            minAltitude: coord.minAltitude,
            maxAltitude: coord.maxAltitude,
            radius: coord.radius,
            activeidentityid:infoid,
            index: index
            })))
          // console.log(this.gisdata.circular);
    },


    polygonalpush(detail,index,infoid){
      // 第一句话后续可以去掉 注意数据类型
      // detail=JSON.parse(detail.replace(/([{,])\s*([a-zA-Z_]\w*)\s*:/g, '$1"$2":'));
      console.log("typeof detail:",typeof detail);
      console.log("多边形detail",detail);
      const polygonalData = {
    coordinates: [],  // 存放经纬度数组
    minAltitude: null,  // 存放最小高度数组
    maxAltitude: null, // 存放最大高度数组
    index: index,
    activeidentityid:infoid

  };
  const firstPoint = detail[0];
  polygonalData.minAltitude = firstPoint.minAltitude;
  polygonalData.maxAltitude = firstPoint.maxAltitude;

  detail.forEach(point => {
    // 将经纬度信息推入 coordinates 数组
    polygonalData.coordinates.push({
              longitude: point.longitude,
              latitude: point.latitude
            });
  });
  console.log(polygonalData);
  this.gisdata.polygonal.push(polygonalData);
    },


    straightpush(detail,index,infoid){
       // 第一句话后续可以去掉 注意数据类型
      //  detail=JSON.parse(detail.replace(/([{,])\s*([a-zA-Z_]\w*)\s*:/g, '$1"$2":'));
      console.log('typeof detail:',typeof detail);
      console.log('点线形detail',detail);
      const straightData = {
    coordinates: [],  // 存放经纬度高数组
    index: index,
    activeidentityid:infoid
  };
  detail.forEach(point => {
    // 将经纬度信息推入 coordinates 数组
    straightData.coordinates.push({
              longitude: point.longitude,
              latitude: point.latitude,
              altitude: point.altitude
            });                                                                                  
           
  });
  console.log(straightData);
  this.gisdata.straight.push(straightData);


    }


  },

  watch: {
    // 监听 statusDialogVisible 的变化
    statusDialogVisible(newValue, oldValue) {
      if (newValue === false && oldValue === true) {
        // 当 statusDialogVisible 从 1 变为 0 时，调用子组件的 resetSelection 方法
        this.$refs.customTable.resetSelection();
        // console.log('resetSelection called');
      }
    }
  }

}
</script>


<style scoped lang="css" src="@/assets/indexModule2PS.css" />
